package com.larly.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * IP地址工具类
 */
@Slf4j
@Component
public class IpAddressUtil {

    /**
     * 获取客户端真实IP地址
     *
     * @param request 请求对象
     * @return IP地址
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多个IP地址时，取第一个非unknown的有效IP地址
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }

        // 处理IPv6本地回环地址
        if ("0:0:0:0:0:0:0:1".equals(ip) || "::1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    /**
     * 通过IP地址获取地理位置信息
     *
     * @param ip IP地址
     * @return 地理位置信息
     */
    public static String getRegionByIp(String ip) {
        try {
            // 使用免费的IP地址查询服务
            String url = "http://ip-api.com/json/" + ip + "?lang=zh-CN";
            HttpResponse response = HttpRequest.get(url).timeout(5000).execute();
            if (response.getStatus() == 200) {
                String body = response.body();
                Map<String, Object> resultMap = JSONUtil.toBean(body, HashMap.class);
                if ("success".equals(resultMap.get("status"))) {
                    String country = (String) resultMap.get("country");
                    String regionName = (String) resultMap.get("regionName");
                    String city = (String) resultMap.get("city");
                    if (country != null && regionName != null && city != null) {
                        return country + "-" + regionName + "-" + city;
                    } else if (country != null) {
                        return country;
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取IP地址地理位置失败", e);
        }
        return "未知";
    }
}
